package com.hh.gen;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hh.gen.entity.domain.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * MP注入处理器
 *
 * @author auto
 * @date 2021/4/25
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                LocalDateTime current = ObjectUtil.isNotNull(baseEntity.getCreateTime()) ? baseEntity.getCreateTime() : LocalDateTime.now();
                baseEntity.setCreateTime(current);
                baseEntity.setUpdateTime(current);
                // 当前已登录 且 创建人为空 则填充
                baseEntity.setCreator("自动生成代码");
                // 当前已登录 且 更新人为空 则填充
                baseEntity.setUpdater("自动生成代码");
                // 当前已登录 且 创建人为空 则填充
                baseEntity.setCreatorName("自动生成代码名称");
                // 当前已登录 且 更新人为空 则填充
                baseEntity.setUpdaterName("自动生成代码名称");
            }
        } catch (Exception e) {
            log.error("自动注入异常 => {}", e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                LocalDateTime current = LocalDateTime.now();
                // 更新时间填充(不管为不为空)
                baseEntity.setUpdateTime(current);
                // 当前已登录 更新人填充(不管为不为空)
                if (CharSequenceUtil.isNotBlank("自动生成代码")) {
                    baseEntity.setUpdater("自动生成代码");
                    baseEntity.setUpdaterName("自动生成代码名称");
                }
            }
        } catch (Exception e) {
            throw new BaseException("自动注入异常 => " + e.getMessage(), String.valueOf(HttpStatus.HTTP_UNAUTHORIZED));
        }
    }
}
